package cn.thinkjoy.LawDataForExcel.quartz;
import cn.thinkjoy.LawDataForExcel.bean.ApunishNoticeInfo;
import cn.thinkjoy.LawDataForExcel.bean.CompanyInfo;
import cn.thinkjoy.LawDataForExcel.bean.Databean;
import cn.thinkjoy.LawDataForExcel.bean.PunishTypeInfo;
import cn.thinkjoy.LawDataForExcel.email.EmailMessage;
import cn.thinkjoy.LawDataForExcel.excel.PoIExcelInPut;
import cn.thinkjoy.LawDataForExcel.extractURL.HtmlUnitSearchWeb;
import cn.thinkjoy.LawDataForExcel.service.Impl.ApunishNoticeInfoServiceImpl;
import cn.thinkjoy.LawDataForExcel.service.Impl.CompanyInfoServiceImpl;
import cn.thinkjoy.LawDataForExcel.service.redis.SingleCommonCacheService;
import cn.thinkjoy.LawDataForExcel.util.UtilZipFile;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by thinkjoy on 2017/6/22.
 * 处理好的数据导出excel并发送到相应邮箱
 */
public class QuartzApplication {

    @Autowired
    CompanyInfoServiceImpl companyInfoService;
    @Autowired
    SingleCommonCacheService<CompanyInfo> redisCompanyInfo;
    @Autowired
    ApunishNoticeInfoServiceImpl apunishNoticeInfoService;

    public void execute(){
        System.out.println("开始执行");
        CompanyInfo companyInfo;
        Map<Object,List> maps=new HashMap<>();
        String currentDate=new SimpleDateFormat("yyyy/MM/dd").format(new Date());
//        String currentDate="2017/06/29";
//        Databean databean=new Databean();
//        databean.setStartdate("2017/06/26");
//        databean.setEnddate("2017/06/30");
//        查找出当天的交通违法信息
        List<ApunishNoticeInfo> apunishNoticeInfos=apunishNoticeInfoService.findNoticesByDate(currentDate);
//        查找出当天的处罚事由
        List<PunishTypeInfo> punishTypeInfos=apunishNoticeInfoService.findPunishReasonByDate(currentDate);
//        将list存进map里
        for(PunishTypeInfo punishTypeInfo:punishTypeInfos){
            List<ApunishNoticeInfo> noticeList=new ArrayList<>();
            maps.put(punishTypeInfo,noticeList);
        }
        if(apunishNoticeInfos.size()!=0){
            for(ApunishNoticeInfo apunishNoticeInfo:apunishNoticeInfos){
                //查找并赋值企业工商信息
                if(apunishNoticeInfo.getPtype().equals("企业/法人代表")){
                    String cname=apunishNoticeInfo.getAdminiName();
                    companyInfo=companyInfoService.findCompanyInfoByName(cname.trim());
                    if(companyInfo==null){
                        try {
                            String copyname=cname;
                            if(cname.indexOf("(")!=-1 && cname.indexOf(")")!=-1){
                                cname=cname.replaceAll("\\(","").replaceAll("\\)","");
                            }else if (cname.indexOf("（")!=-1 && cname.indexOf("）")!=-1){
                                cname=cname.replaceAll("（","").replaceAll("）","");
                            }
                            HtmlUnitSearchWeb htmlUnitSearchWeb=new HtmlUnitSearchWeb(cname.trim(),copyname);
                            companyInfo=htmlUnitSearchWeb.AdvanceSearch();
                            if(companyInfo!=null){
                                System.out.println("爬取到的数据："+companyInfo.toString());
                                companyInfoService.saveCompanyInfo(companyInfo);
                                redisCompanyInfo.setCacheObject(copyname,companyInfo);
                            }else {
                                System.out.println("数据爬取失败!");
                            }
                            Thread.sleep(20000);//休眠20s
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("休眠时间到");
                    }
                    if(companyInfo!=null){
                        apunishNoticeInfo.setRegistnumber(companyInfo.getRegistnumber());
                        apunishNoticeInfo.setOrganiznumber(companyInfo.getOrganiznumber());
                        apunishNoticeInfo.setLegalname(companyInfo.getLegalname());
                        apunishNoticeInfo.setCreditnumber(companyInfo.getCreditnumber());
                        apunishNoticeInfo.setTaxnumber(companyInfo.getTaxnumber());
                    }
                    apunishNoticeInfo.setIdNumber("");
                }
                //分类
                for (Map.Entry<Object, List> entry : maps.entrySet()) {
                    if (apunishNoticeInfo.getPunishReason().equals(transObj(entry.getKey()))){
                        entry.getValue().add(apunishNoticeInfo);
                    }
                }
            }
            Thread.yield();
//            执行生成Excel
            String dirpath=null;
            for (Map.Entry<Object, List> entry : maps.entrySet()) {
                if(entry.getValue().size()>0){
                    PoIExcelInPut poIExcelInPut=new PoIExcelInPut();
                    dirpath=poIExcelInPut.createExcel(entry.getValue());
                }
            }
            //将生成的文件进行压缩并发送邮件
            if(dirpath!=null){
                File f=new File(dirpath);
                new UtilZipFile(new File(dirpath+".zip")).zipFiles(f);
                EmailMessage message=new EmailMessage();
                message.sendMail(dirpath+".zip");
                if(apunishNoticeInfoService.updateStatus(apunishNoticeInfos)>0){
                    System.out.println("经过处理的数据，状态已经变为1");
                }
            }else{
                System.out.println("生成excel流程出错,请重试");
            }
        }else {
            System.out.println("没有数据");
        }
    }

    //    对象强制转换
    public String transObj(Object o) {
        PunishTypeInfo p = (PunishTypeInfo) o;
        return p.getPunishReason();
    }
}
